package com.leon.learnenginespace.drools.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * @author DJ032474
 */
public class RuleCoverJsonUtils {
    public static boolean getIsArray(String str) {
        char[] keyChars = str.toCharArray();
        int keyLength = keyChars.length;
        if (keyLength == 0) {
            return false;
        }
        return '#' == keyChars[keyLength - 1];
    }

    /**
     * 获取putKey
     *
     * @param str
     * @param isArray
     * @return
     */
    public static String getPutKey(String str, boolean isArray) {
        if (isArray) {
            str = str.substring(0, str.length() - 1);
        }
        return str;
    }

    /**
     * 转换数组
     *
     * @param str
     * @return
     */
    public static String[] getStringArray(String str) {
        String[] strs = str.split("\\.");
        if (strs == null || strs.length == 0) {
            strs = new String[]{str};
        }
        return strs;
    }

    /**
     * 上级节点是JSONOBJECT,添加value
     *
     * @param key
     * @param value
     * @param isArray
     * @param superJson
     */
    public static JSON nodeAddNewNode(String key, Object value, Boolean isArray, JSON superJson) {
        JSONArray jsonArray = new JSONArray();
        JSONObject json = (JSONObject) superJson;
        if (value instanceof List && isArray) {
            jsonArray.addAll((List) value);
        } else if (isArray) {
            jsonArray.add(value);
        } else if (value instanceof Map && StringUtils.isEmpty(key)) {
            json.putAll((Map) value);
            return json;
        } else if (value instanceof Map) {
            JSONObject temp = new JSONObject();
            temp.putAll((Map) value);
            json.put(key, temp);
            return temp;
        } else {
            json.put(key, value);
            return json;
        }

        json.put(key, jsonArray);
        return jsonArray;
    }

    /**
     * 添加数组结点
     *
     * @param key
     * @param value
     * @param isArray
     * @param superJson
     * @return
     */
    public static JSON nodeAddNewArrayNode(String key, Object value, Boolean isArray, JSON superJson) {
        JSONArray jsonArray = null;
        JSONObject json = (JSONObject) superJson;
        if (isArray && json.get(key) == null) {
            jsonArray = new JSONArray();
        } else {
            jsonArray = json.getJSONArray(key);
        }
        if (value instanceof List && isArray) {
            jsonArray.addAll((List) value);
        } else if (!isArray && value instanceof Map) {
            json.putAll((Map) value);
            return json;
        } else {
            jsonArray.add(value);
        }

        json.put(key, jsonArray);
        return jsonArray;
    }

    /**
     * 添加节点
     * @param key
     * @param value
     * @param isArray
     * @param superJson
     * @return
     */
    public static JSON nodeAdd(String key, Object value, Boolean isArray, JSON superJson) {
        if (isArray) {
            superJson = nodeAddNewArrayNode(key, value, isArray, superJson);
        } else {
            superJson = nodeAddNewNode(key, value, isArray, superJson);
        }
        return superJson;
    }

    /**
     * 数组添加节点
     *
     * @param key
     * @param value
     * @param isArray
     * @param superJson
     * @return
     */
    public static JSON arrayAdd(String key, Object value, Boolean isArray, JSON superJson) {
        JSONArray superJsonArray = (JSONArray) superJson;
        JSONObject json = new JSONObject();
        boolean isAddArray = json.isEmpty();
        if (!isArray) {
            json.put(key, value);
            if (isAddArray) {
                superJsonArray.add(json);
            }
            return json;
        } else if (key != null) {
            JSONArray tempTopJsonArray = new JSONArray();
            if (value instanceof List && isArray) {
                tempTopJsonArray.addAll((List) value);
            } else {
                tempTopJsonArray.add(value);
            }
            json.put(key, tempTopJsonArray);
            superJsonArray.add(json);
            return json;
        } else {
            superJsonArray.add(value);
            return superJsonArray;
        }

    }

    /**
     * 处理中间节点数组
     *
     * @param isSuperJsonObject
     * @param putKey
     * @param superNodeJson
     * @return
     */
    public static JSONArray processArray(boolean isSuperJsonObject, String putKey, JSON superNodeJson) {
        JSONArray superJsonArray = null;

        if (isSuperJsonObject) {
            JSONObject superJson = (JSONObject) superNodeJson;
            superJsonArray = superJson.getJSONArray(putKey);
            if (superJsonArray != null) {
                return superJsonArray;
            }
            superJsonArray = new JSONArray();
            superJson.put(putKey, superJsonArray);

        } else {
            superJsonArray = (JSONArray) superNodeJson;
            JSONArray jsonArray = new JSONArray();
            JSONObject json = new JSONObject();
            json.put(putKey, jsonArray);
            superJsonArray.add(json);
            return jsonArray;
        }
        return superJsonArray;
    }

    /**
     * 数据封装
     *
     * @param entry
     * @param body
     * @param value
     * @return
     */
    public static JSON encap(String entry, JSONObject body, Object value) {
        JSON superNodeJson;
        if (entry == null || entry.length() == 0) {
            superNodeJson = leafNode("", value, false, body, true);
            return superNodeJson;
        }
        superNodeJson = body;
        String[] entryArray = getStringArray(entry);
        String key = null;
        int size = entryArray.length;
        JSONObject topJson = null;
        JSONArray topJsonArray = null;
        boolean isTopJsonObject = true;
        String putKey = null;
        boolean isArray = false;
        boolean isLeafNode = false;
        for (int i = 0; i < size; i++) {
            isLeafNode = (i + 1 == size);
            key = entryArray[i];
            isArray = getIsArray(key);
            putKey = getPutKey(key, isArray);
            //叶子节点处理开始
            if (isLeafNode) {
                superNodeJson = leafNode(putKey, value, isArray, superNodeJson, isTopJsonObject);
                return superNodeJson;
            }
            //叶子节点处理结束
            //路径处理开始
            if (isArray) {
                topJsonArray = processArray(isTopJsonObject, putKey, superNodeJson);
                superNodeJson = topJsonArray;
                isTopJsonObject = false;
            } else {
                topJson = processJSONObject(isTopJsonObject, superNodeJson, putKey);
                superNodeJson = topJson;
                isTopJsonObject = true;
            }
        }
        return superNodeJson;
    }

    /**
     * 处理中间节点对象
     *
     * @param isSuperJsonObject
     * @param superNodeJson
     * @param putKey
     * @return
     */
    public static JSONObject processJSONObject(boolean isSuperJsonObject, JSON superNodeJson, String putKey) {
        JSONObject superJson = null;
        JSONObject json = null;
        if (isSuperJsonObject) {
            superJson = (JSONObject) superNodeJson;
            json = superJson.getJSONObject(putKey);
            if (json != null) {
                return json;
            }
            json = new JSONObject();
            superJson.put(putKey, json);
        } else {
            JSONArray superJsonArray = (JSONArray) superNodeJson;
            json = new JSONObject();
            superJsonArray.add(json);
        }
        return json;

    }

    /**
     * 处理叶子节点
     *
     * @param key
     * @param value
     * @param isArray
     * @param superJson
     * @param isTopJsonObject
     * @return
     */
    public static JSON leafNode(String key, Object value, Boolean isArray, JSON superJson, boolean isTopJsonObject) {
        if (isTopJsonObject) {
            superJson = nodeAdd(key, value, isArray, superJson);
        } else {
            superJson = arrayAdd(key, value, isArray, superJson);
        }
        return superJson;
    }

    /**
     * 拼接key
     * @param i
     * @param size
     * @param paths
     * @return
     */
    public static String getParamKey(int i, int size, String[] paths) {
        String key = "";
        for (; i < size; i++) {
            key += StringUtils.isEmpty(key)?"":".";
            key += paths[i];
        }
        return key;
    }

    /**
     * 获取单节点value
     * @param path
     * @param body
     * @return
     */
    public  static String getNodeValue(String path, JSONObject body){
        if(path.indexOf("#") != -1){
            throw new FieldException("词条路径不支持数组");
        }
        String[] paths = RuleCoverJsonUtils.getStringArray(path);
        int size = paths.length;
        boolean isArray = false;
        boolean isLeafNode = false;
        String key = null;
        String getKey = null;
        JSONObject superJson = body;
        for (int i = 0; i < size; i++) {
            isLeafNode = (i + 1 == size);
            key = paths[i];
            isArray = getIsArray(key);
            getKey = getPutKey(key, isArray);
            if (isLeafNode) {
                return superJson.getString(getKey);
            }
            superJson = superJson.getJSONObject(getKey);
            if (superJson == null) {
                throw new FieldException("词条路径不完整");
            }
        }
        return null;
    }

    /**
     * 处理父级节点为是单节点
     * @param isArray
     * @param getKey
     * @param superJson
     * @return
     */
    public static JSON superJsonProcess(boolean isArray, String getKey, JSON superJson) {
        JSONObject superJsonObject = (JSONObject) superJson;
        if (isArray) {
            superJson = superJsonObject.getJSONArray(getKey);
        } else {
            superJson = superJsonObject.getJSONObject(getKey);
        }
        return superJson;
    }
    /**
     * 处理父级节点为是数组
     * @param isArray
     * @param getKey
     * @param superJson
     * @return
     */
    public static boolean superJsonArrayProcess(boolean isArray, String getKey, JSON superJson,int i, int size, String[] paths, String value, String operationType, String dataType,boolean isSuperArray, String paramNum) {
        JSONArray superJsonArray = null;
        int arrayLength = 0;
        if(isSuperArray) {
            superJsonArray = (JSONArray) superJson;
            arrayLength = superJsonArray.size();
        } else {
            JSONObject superJsonObject = (JSONObject) superJson;
            superJsonArray = superJsonObject.getJSONArray(getKey);
            arrayLength = superJsonArray.size();
        }

        String paramKey = null;
        boolean isResult = false;
        if (isArray) {
            paramKey = RuleCoverJsonUtils.getParamKey(i + 1, size, paths);
            isResult = operationArray(paramKey, getKey, superJsonArray, value, operationType, dataType, paramNum);
            if (isResult) {
                return isResult;
            }
        } else {
            paramKey = RuleCoverJsonUtils.getParamKey(i + 1, size, paths);
            for (int j = 0; j < arrayLength; j++) {
                isResult = OperationUtils.operation(paramKey, superJsonArray.getJSONObject(j), value, operationType, dataType,paramNum);
                if (isResult) {
                    return isResult;
                }
            }
        }
        return false;
    }
    /**
     * 运算数组处理
     * @param key
     * @param getKey
     * @param jsonArray
     * @param value
     * @param operationType
     * @param dateType
     * @return
     */
    private static boolean operationArray(String key, String getKey, JSONArray jsonArray, String value, String operationType,String dateType, String paramNum){
        int size = jsonArray.size();
        JSONArray tempJsonArray = null;
        String[] paths = RuleCoverJsonUtils.getStringArray(key);
        JSONObject jsonObject = null;
        String tempKey = null;
        boolean isArray = false;
        String tempGetKey = null;
        String paramKey = null;
        boolean isResult = false;
        for (int i = 0; i < size; i++) {
            jsonObject = jsonArray.getJSONObject(i);
            tempKey = paths[i];
            isArray = RuleCoverJsonUtils.getIsArray(tempKey);
            tempGetKey = RuleCoverJsonUtils.getPutKey(tempKey, isArray);

            paramKey = RuleCoverJsonUtils.getParamKey(i+1, size, paths);
            if(isArray){
                tempJsonArray = jsonObject.getJSONArray(tempGetKey);
                isResult = operationArray( paramKey,  tempGetKey,  jsonArray,  value,  operationType,dateType, paramNum);
                if(isResult){
                    return isResult;
                }
            }else{
                isResult = OperationUtils.operation(tempGetKey, jsonObject,  value,  operationType,dateType, paramNum);
                if(isResult){
                    return isResult;
                }
            }
        }
        return false;
    }
    /**
     * 获取非叶子节点以外的词条路径
     * @param filedPath
     * @return
     */
    public static String getNotLeadNodeFiledPath(String filedPath) {
        int index =filedPath.lastIndexOf(".");
        return filedPath.substring(0, index);
    }
    /**
     * 获取叶子节点词条名称
     * @param filedPath
     * @return
     */
    public static String getLeadNodeFiledName(String filedPath) {
        int aaIndex =filedPath.lastIndexOf(".");
        return filedPath.substring(aaIndex + 1);
    }
    /**
     * 获取数组对象
     * @param path
     * @param body
     * @return
     */
    public static JSONArray getArrayNode(String path, JSONObject body) {
        String[] paths = RuleCoverJsonUtils.getStringArray(path);
        int size = paths.length;
        boolean isArray = false;
        String key = null;
        String getKey = null;
        JSONObject superJson = body;
        for (int i = 0; i < size; i++) {
            key = paths[i];
            isArray = getIsArray(key);
            getKey = getPutKey(key, isArray);
            if(isArray) {
                return superJson.getJSONArray(getKey);
            }
            superJson = superJson.getJSONObject(getKey);
            if (superJson == null) {
                throw new FieldException("词条路径不完整");
            }
        }
        return null;
    }

    /**
     * 获取数组对象的子key
     * @param path
     * @return
     */
    public static String getArrayNodeSubKey(String path) {
        String[] paths = path.split("#");
        String tempPath = "";
        System.out.println(paths[1].indexOf(".") );
        for (int i = 1; i < paths.length; i++) {
            if(i == 1) {
                if(paths[i].indexOf(".") == 0) {
                    tempPath += paths[i].substring(1);
                } else {
                    tempPath += paths[i];
                }
            }else {
                tempPath += "#" + paths[i];
            }
        }
        return tempPath;
    }
    public static void main(String[] args) {
        String path = "aa#.bb.CC#.cc";
        String[] paths = path.split("#");
        String tempPath = "";
        System.out.println(paths[1].indexOf(".") );
        for (int i = 1; i < paths.length; i++) {
            if(i == 1) {
                if(paths[i].indexOf(".") == 0) {
                    tempPath += paths[i].substring(1);
                } else {
                    tempPath += paths[i];
                }
            } else {
                tempPath += "#" + paths[i];
            }
        }
        System.out.println(tempPath);
    }
}

